/**
 * <p>DemoActivity Class</p>
 *
 * @author zhuzhenlei 2014-7-17
 * @version V1.0
 * @modificationHistory
 * @modify by user:
 * @modify by reason:
 */
package com.test.demo;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.hikvision.netsdk.ExceptionCallBack;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_DEVICEINFO_V30;
import com.test.demo.activity.PlayBackActivity;
import com.test.demo.base.BaseActivity;
import com.test.demo.utils.ScreenUtils;
import com.test.demo.utils.ToastUtil;
import com.test.demo.widget.RLPlaySurfaceView;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 监控列表显示
 */
public class DemoMainActivity extends BaseActivity implements Callback {
    private final String TAG = "DemoActivity";
    private static final String IP = "192.168.1.104";
    private static final int PORT = 8000;
    private static final String UNAME = "admin";
    private static final String UPWD = "gyzn2018";

    @BindView(R.id.Sur_Player)
    SurfaceView mSurPlayer;
    @BindView(R.id.rl_jk_list)
    RelativeLayout rlJkList;

    private int m_iStartChan;//开始通道
    private int m_iChanNum;//通道总个数
    private static RLPlaySurfaceView[] players;
    private static Integer[] colors = {Color.parseColor("#ff0000"), Color.parseColor("#00ff00"), Color.parseColor("#0000ff")
            , Color.parseColor("#0000ff"), Color.parseColor("#00ff00"), Color.parseColor("#ff0000"), Color.parseColor("#ff0000")
            , Color.parseColor("#00ff00"), Color.parseColor("#0000ff")};
    private int layoutType = 9;//默认显示布局（1，4，9）
    private int surfaceMax = 9;//最大个数
    private int mLogId;
    private int swPaddingLeft = 20;
    private int swPaddingTop = 10;
    private int leftMargin = 30;
    private int topMargin = 50;
    private int bottomMargin = 10;
    private int mCameraListWidth;
    private Context mContext;
    private int curChanle;
    private Handler handler = new Handler();

    @Override
    public int getContentView() {
        return R.layout.layout_main;
    }

    @Override
    protected void init() {
        mContext = this;

        players = new RLPlaySurfaceView[layoutType];
        initSdk();
        mSurPlayer.setZOrderOnTop(true);
        mSurPlayer.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mSurPlayer.getHolder().addCallback(this);
        //<0 表示登录失败
        mLogId = loginNormalDevice();
        if (mLogId < 0) {
            ExceptionCallBack oexceptionCbf = getExceptiongCbf();
            if (!HCNetSDK.getInstance().NET_DVR_SetExceptionCallBack(oexceptionCbf)) {
                Log.i(TAG, "NET_DVR_SetExceptionCallBack is failed!");
            }
        } else {
            previewCameraList();
        }
    }

    private void previewCameraList() {
        rlJkList.post(new Runnable() {
            @Override
            public void run() {//动态添加SurfaceView
                DisplayMetrics metric = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metric);
                int widthPixels1 = metric.widthPixels;
                mCameraListWidth = rlJkList.getWidth();
                int x = layoutType == 1 ? 1 : layoutType == 4 ? 2 : 3;
                if (x == 1) {
                    swPaddingLeft = 0;
                    swPaddingTop = 0;
                } else {
                    swPaddingLeft = 20;
                    swPaddingTop = 10;
                }
                int titleHeight = ScreenUtils.dip2px(mContext, 36);//标题高度
                int a = widthPixels1 - mCameraListWidth;
                int sw;
                if (x > 1) {
                    sw = (mCameraListWidth - leftMargin * 2 - swPaddingLeft * (x - 1)) / x;
                } else {
                    sw = (mCameraListWidth - leftMargin * 2);
                }
                int sh = ((sw * 3) / 4) + titleHeight;

                for (int i = 0; i < layoutType; i++) {
                    players[i] = new RLPlaySurfaceView(mContext);
                    players[i].setTitle("监控" + (i + 1));
                    final RLPlaySurfaceView player = players[i];
                    final int finalI = i;
                    player.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (player != null) {
                                curChanle = m_iStartChan + finalI;
                                boolean checked = player.isChecked();
                                if (!checked) {//没有选中，设置选中
                                    for (RLPlaySurfaceView temp : players) {
                                        temp.setChecked(false);
                                    }
                                    player.setChecked(true);
                                }
                            }
                        }
                    });
                    players[i].getPlaySurfaceView().setParam(sw * 2);
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            FrameLayout.LayoutParams.WRAP_CONTENT,
                            FrameLayout.LayoutParams.WRAP_CONTENT);

                    params.leftMargin = a + leftMargin + (sw + swPaddingLeft) * (i % x);
                    params.topMargin = topMargin + (sh + swPaddingTop) * ((i / x) % x);
                    addContentView(players[i], params);
                    players[i].setVisibility(View.INVISIBLE);
                }
                for (int i = 0; i < layoutType; i++) {
                    players[i].setVisibility(View.VISIBLE);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < layoutType; i++) {
                                players[i].getPlaySurfaceView().setVisibility(View.VISIBLE);
                                players[i].getPlaySurfaceView().startPreview(mLogId, m_iStartChan + i);
                            }
                        }
                    }, 1000);
                }
            }
        });
    }

    /**
     * 获取当前选中的监控
     *
     * @return
     */
    private int getCheckedSurface() {
        for (int i = 0; i < players.length; i++) {
            RLPlaySurfaceView sv = players[i];
            if (sv != null) {
                if (sv.isChecked()) {
                    return i;
                }
            }
        }
        return -1;
    }

    @OnClick({R.id.btn_layout_one, R.id.btn_layout_four, R.id.btn_layout_nine, R.id.btn_layout_pre_back, R.id.iv_full_screen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_layout_one:
                layoutType = 1;
                resetLayout();
                break;
            case R.id.btn_layout_four:
                layoutType = 4;
                resetLayout();
                break;
            case R.id.btn_layout_nine:
                layoutType = 9;
                resetLayout();
                break;
            case R.id.btn_layout_pre_back:
                int checkedSurface = getCheckedSurface();
                if (checkedSurface == -1) {
                    ToastUtil.TextToast(this, "请选择回放监控");
                    return;
                }
                startActivity(new Intent(this, PlayBackActivity.class)
                        .putExtra("m_iLogID", mLogId)
                        .putExtra("m_iStartChan", curChanle));
                break;
            case R.id.iv_full_screen:
                int checkedSurfaceFull = getCheckedSurface();
                if (checkedSurfaceFull == -1) {
                    ToastUtil.TextToast(this, "请选择监控");
                    return;
                }
                // TODO: 2019/8/7 跳转到回放
                break;
        }
    }

    private boolean initSdk() {
        if (!HCNetSDK.getInstance().NET_DVR_Init()) {
            Log.e(TAG, "HCNetSDK init is failed!");
            return false;
        }
        HCNetSDK.getInstance().NET_DVR_SetLogToFile(3, "/mnt/sdcard/sdklog/", true);
        return true;
    }

    /**
     * 登录设备
     *
     * @return
     */
    private int loginNormalDevice() {
        NET_DVR_DEVICEINFO_V30 m_oNetDvrDeviceInfoV30 = new NET_DVR_DEVICEINFO_V30();
        if (null == m_oNetDvrDeviceInfoV30) {
            Log.i(TAG, "HKNetDvrDeviceInfoV30 new is failed!");
            return -1;
        }
        int iLogID = HCNetSDK.getInstance().NET_DVR_Login_V30(IP, PORT, UNAME, UPWD, m_oNetDvrDeviceInfoV30);
        if (iLogID < 0) {
            Log.i(TAG, "NET_DVR_Login is failed!Err:" + HCNetSDK.getInstance().NET_DVR_GetLastError());
            return -1;
        }
        if (m_oNetDvrDeviceInfoV30.byChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byChanNum;
        } else if (m_oNetDvrDeviceInfoV30.byIPChanNum > 0) {
            m_iStartChan = m_oNetDvrDeviceInfoV30.byStartDChan;
            m_iChanNum = m_oNetDvrDeviceInfoV30.byIPChanNum + m_oNetDvrDeviceInfoV30.byHighDChanNum * 256;
        }
        Log.i(TAG, "loginNormalDevice: m_iChanNum = " + m_iChanNum);
        return iLogID;
    }

    private void resetLayout() {
        for (RLPlaySurfaceView sv : players) {
            if (sv != null) {
                ViewGroup vp = (ViewGroup) sv.getParent();
                vp.removeView(sv);
                sv.getPlaySurfaceView().stopPreview();
                sv.getPlaySurfaceView().setVisibility(View.GONE);
            }
        }
        HCNetSDK.getInstance().NET_DVR_Logout_V30(mLogId);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                init();
            }
        }, 1000);
    }

    private ExceptionCallBack getExceptiongCbf() {
        return new ExceptionCallBack() {
            public void fExceptionCallBack(int iType, int iUserID, int iHandle) {
                System.out.println("recv exception, type:" + iType);
            }
        };
    }

    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surface create");
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.i(TAG, "surface changed");
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "Player setVideoWindow release!");
    }

}